package com.zqwh.xtool.api.offline;

import android.content.Context;

import com.zqwh.xtool.greendao.DaoManager;
import com.zqwh.xtool.greendao.UserDao;
import com.zqwh.xtool.greendao.db.User;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

public class UserResposity {
    private DaoManager daoManager;
    private UserDao userDao;

    public UserResposity(Context context){
        daoManager = DaoManager.getInstance();
        daoManager.init(context);
        userDao = daoManager.getDaoSession().getUserDao();
    }

    /**
     * 插入记录
     *
     * @param user
     * @return
     */
    public boolean insertUser(User user) {
        return userDao.insertOrReplace(user) != -1;
    }

    /**
     * 修改记录
     * @param user
     */
    public void updateUser(User user){
        userDao.update(user);
    }

    /**
     * 插入多条记录
     * @param userList
     * @return
     */
    public boolean insertMultUser(final List<User> userList){
        boolean flag = false;
        try {
            daoManager.getDaoSession().runInTx(new Runnable() {
                @Override
                public void run() {
                    for (User user : userList) {
                        userDao.insertOrReplace(user);
                    }
                }
            });
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 查询所有记录
     * @return
     */
    public List<User> queryAllUser(){
        return userDao.loadAll();
    }

    /**
     * 根据账号密码查询用户
     * @param account
     * @param password
     * @return
     */
    public List<User> queryUserByAccountAndPwd(String account, String password){
        QueryBuilder<User> qb = userDao.queryBuilder();
        qb.where(UserDao.Properties.Valid.eq(true),
                UserDao.Properties.Username.eq(account),
                UserDao.Properties.Password.eq(password));
        return qb.list();
    }

    /**
     * 根据IC卡号查询用户
     * @param cardNo
     * @return
     */
    public User queryUserByCardNo(String cardNo){
        QueryBuilder<User> qb = userDao.queryBuilder();
        qb.where(UserDao.Properties.CardNo.eq(cardNo));
        return qb.unique();
    }

    /**
     * 根据ID查询用户
     * @param userId
     * @return
     */
    public User queryUserByUserId(Long userId){
        QueryBuilder<User> qb = userDao.queryBuilder();
        qb.where(UserDao.Properties.UserId.eq(userId));
        return qb.unique();
    }

}
